package com.nova.edc.service.collect.impl;

import com.nova.edc.model.system.AreaPoint;
import com.nova.edc.service.collect.CloudConstant;
import com.nova.edc.service.collect.StatusService;
import com.nova.frame.utils.JdbcUtils;
import com.nova.frame.utils.StringUtils;
import org.apache.commons.dbutils.ResultSetHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by lenovon on 2016/1/28.
 */
public class StatusServiceImpl implements StatusService {

    // 获取当前节点的工作状态
    @Override
    public Integer getStatusByPoint(String gatewayid, Integer sensorid, Integer channelId) {
        Integer value = JdbcUtils.get("select value from data " +
                "where gateway_logo = ? " +
                "and sensor_name = ? " +
                "and channel_name = ?", new ResultSetHandler<Integer>() {
            @Override
            public Integer handle(ResultSet resultSet) throws SQLException {
                while (resultSet.next()) {
                    return resultSet.getInt(1);
                }
                return CloudConstant.STATUS_UNWORK;
            }
        }, gatewayid, sensorid, channelId);
        return value;
    }

    @Override
    public void wrapAreaPoint(AreaPoint areaPoint) {
        if (StringUtils.isNotNullOrEmpty(areaPoint.getGatewayid()) && areaPoint.getSensorid() != null && areaPoint.getChannelid() != null) {
            Integer status = getStatusByPoint(areaPoint.getGatewayid(), areaPoint.getSensorid(), areaPoint.getChannelid());
            areaPoint.setStatus(status);
            areaPoint.setStatusName(getStatusName(status));
        }

    }

    @Override
    public void wrapAreaPoint(List<AreaPoint> areaPoints) {
        for (AreaPoint areaPoint : areaPoints) {
            wrapAreaPoint(areaPoint);
        }
    }

    public String getStatusName(Integer status) {
        switch (status) {
            case CloudConstant.STATUS_ON:
                return CloudConstant.STATUS_ON_NAME;
            case CloudConstant.STATUS_OFF:
                return CloudConstant.STATUS_OFF_NAME;
            case CloudConstant.STATUS_UNWORK:
                return CloudConstant.STATUS_UNWORK_NAME;
        }
        return CloudConstant.STATUS_UNWORK_NAME;
    }
}
